package com.business_clean.ui.fragment.addproject;


import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.SizeUtils;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseFragment;
import com.business_clean.app.config.ConstantMMVK;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.ext.LoadingDialogExtKt;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.ChoosePicUtil;
import com.business_clean.app.uitl.MMKVHelper;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.uitl.UploadFileHelper;
import com.business_clean.data.mode.members.HealthyEntity;
import com.business_clean.data.mode.members.IDCardMemberEntity;
import com.business_clean.data.mode.members.MembersDetailEntity;
import com.business_clean.databinding.FragmentOtherBinding;
import com.business_clean.ui.activity.custom.AddProjectActivity;
import com.business_clean.ui.activity.personnel.SignHandActivity;
import com.business_clean.ui.adapter.GridImageAdapter;
import com.business_clean.viewmodel.request.ProjectMembersViewModel;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.decoration.MyGridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;

import me.hgj.mvvmhelper.ext.AppExtKt;
import me.hgj.mvvmhelper.ext.LogExtKt;

public class OtherFragment extends BaseFragment<ProjectMembersViewModel, FragmentOtherBinding> {

    private GridImageAdapter mUploadAdapter;
    private GridImageAdapter mPicAdapter;

    private GridImageAdapter mCrimeAdapter;
    private String[] strings = {"拍照", "相册"};

    private String uuid = "";

    private int type = 0;

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        mUploadAdapter = new GridImageAdapter(getActivity());
        mUploadAdapter.setSelectMax(9);
        getMDatabind().uploadBodyPic.recyclerview.setAdapter(mUploadAdapter);
        getMDatabind().uploadBodyPic.recyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        getMDatabind().uploadBodyPic.recyclerview.addItemDecoration(new MyGridSpacingItemDecoration(4, SizeUtils.dp2px(10), false));

        mPicAdapter = new GridImageAdapter(getActivity());
        mPicAdapter.setSelectMax(1);
        getMDatabind().uploadPic.recyclerview.setAdapter(mPicAdapter);
        getMDatabind().uploadPic.recyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        getMDatabind().uploadPic.recyclerview.addItemDecoration(new MyGridSpacingItemDecoration(4, SizeUtils.dp2px(10), false));


        mCrimeAdapter = new GridImageAdapter(getActivity());
        mCrimeAdapter.setSelectMax(1);
        getMDatabind().uploadBodyCrime.recyclerview.setAdapter(mCrimeAdapter);
        getMDatabind().uploadBodyCrime.recyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        getMDatabind().uploadBodyCrime.recyclerview.addItemDecoration(new MyGridSpacingItemDecoration(4, SizeUtils.dp2px(10), false));


        getMDatabind().bottom.butBottomButNext.setText(MMKVHelper.getBoolean(ConstantMMVK.IS_ENTRY_SIGN, false) ? "签字并提交" : "提交");

        getMDatabind().uploadPic.tvBaseUploadTitle.setText("头像");
        getMDatabind().uploadPic.tvBaseUploadSub.setText("仅限一张，展示于系统花名册，非必传");
        getMDatabind().uploadBodyPic.tvBaseUploadTitle.setText("健康证明");
        getMDatabind().uploadBodyCrime.tvBaseUploadTitle.setText("无犯罪证明");

        if (!MMKVHelper.getBoolean(ConstantMMVK.IS_UPLOAD_NOT_GUILTY, false)) {//是否需要、上传无犯罪证明
            getMDatabind().uploadBodyCrime.recyclerview.setVisibility(View.GONE);
            getMDatabind().uploadBodyCrime.llBaseUploadLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void lazyLoadData() {
        if (getArguments() != null) {//说明已经存在了
            uuid = getArguments().getString("uuid");
            type = getArguments().getInt("type");
            String application_no = getArguments().getString("application_no");
            if (type == 3) {
                getMDatabind().bottom.butBottomButNext.setText("保存");
            } else {
                getMDatabind().bottom.butBottomButNext.setText(MMKVHelper.getBoolean(ConstantMMVK.IS_ENTRY_SIGN, false) ? "签字并提交" : "提交");
            }

            HashMap<String, String> hashMap = new HashMap<>();
            if (!TextUtils.isEmpty(uuid)) {
                hashMap.put("uuid", uuid);
            }
            if (!TextUtils.isEmpty(application_no)) {
                hashMap.put("application_no", application_no);
            }
            hashMap.put("is_healthy", "1");
            //1是草稿编辑  2是草稿新建 3是档案详情
            if (type == 3) {
                mViewModel.requestStaffDetail(hashMap);//真正的详情
            } else {
                mViewModel.requestMembersDetail(hashMap);//草稿的详情，还没真的成为员工
            }


        }
    }

    @Override
    public void initObserver() {
        //新建的uuid
        App.appViewModelInstance.getCreateUuid().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                uuid = s;
            }
        });
    }

    @Override
    public void onBindViewClick() {
        //头像列表
        mPicAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
            }

            @Override
            public void openPicture() {
                showBottomSelectedPic(1, 1);
            }
        });

        //健康证明
        mUploadAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
            }

            @Override
            public void openPicture() {
                showBottomSelectedPic(9 - mUploadAdapter.getData().size(), 2);
            }
        });


        //无犯罪证明
        mCrimeAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
            }

            @Override
            public void openPicture() {
                showBottomSelectedPic(9 - mCrimeAdapter.getData().size(), 3);
            }
        });


        getMDatabind().bottom.butBottomButLast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                App.appViewModelInstance.getProjectLastPersonnel().setValue(4);
            }
        });
        getMDatabind().bottom.butBottomButNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestCreate();
            }
        });
    }

    /**
     * 打开相册，让选择
     */
    private void showBottomSelectedPic(int size, int channel) {
        CommonUtils.showBottomListWith(getActivity(), 20, "", strings, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                switch (position) {
                    case 0:
                        if (size == 1) {//说明是头像
                            ChoosePicUtil.openCameraCropTake(getMActivity(), new OnResultCallbackListener<LocalMedia>() {
                                @Override
                                public void onResult(ArrayList<LocalMedia> result) {
                                    uploadMedias(result, channel);
                                }

                                @Override
                                public void onCancel() {

                                }
                            });
                        } else {
                            ChoosePicUtil.openCameraTake(getMActivity(), new OnResultCallbackListener<LocalMedia>() {
                                @Override
                                public void onResult(ArrayList<LocalMedia> result) {
                                    uploadMedias(result, channel);
                                }

                                @Override
                                public void onCancel() {

                                }
                            });
                        }
                        break;
                    case 1:
                        if (size == 1) {//说明是头像
                            ChoosePicUtil.openAlbumCrop(getMActivity(), size, new OnResultCallbackListener<LocalMedia>() {
                                @Override
                                public void onResult(ArrayList<LocalMedia> result) {
                                    uploadMedias(result, channel);
                                }

                                @Override
                                public void onCancel() {

                                }
                            });
                        } else {
                            ChoosePicUtil.openAlbum(getMActivity(), size, new OnResultCallbackListener<LocalMedia>() {
                                @Override
                                public void onResult(ArrayList<LocalMedia> result) {
                                    uploadMedias(result, channel);
                                }

                                @Override
                                public void onCancel() {

                                }
                            });
                        }
                        break;
                }
            }
        });
    }

    /**
     * 在这里上传图片
     *
     * @param result
     */
    private void uploadMedias(ArrayList<LocalMedia> result, int channel) {
        LoadingDialogExtKt.showLoadingExt(this, "上传中");
        ArrayList<String> strings1 = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            if (channel == 1) {//头像
                strings1.add(result.get(i).getCutPath());
            } else {
                strings1.add(result.get(i).getCompressPath());
            }
        }
        UploadFileHelper.getInstance().uploadFiles(getActivity(), strings1, UploadFileHelper.PATH_HEADER_PERSONNEL, new UploadFileHelper.UploadListener() {
            @Override
            public void onUploadSuccess(String response) {
                switch (channel) {
                    case 1:
                        mPicAdapter.addItemData(response);
                        break;
                    case 2:
                        mUploadAdapter.addItemData(response);
                        break;
                    case 3:
                        mCrimeAdapter.addItemData(response);
                        break;
                }
                LoadingDialogExtKt.dismissLoadingExt(OtherFragment.this);
            }

            @Override
            public void onUploadFailed(String error) {
                ToastUtil.show("上传失败，请重新尝试");
                LoadingDialogExtKt.dismissLoadingExt(OtherFragment.this);
            }

            @Override
            public void onUploadProgress(int progress) {

            }


        });
    }

    @Override
    public void onRequestSuccess() {
        mViewModel.getUpdatePicStatus().observe(this, new Observer<IDCardMemberEntity>() {
            @Override
            public void onChanged(IDCardMemberEntity idCardMemberEntity) {
                if (type == 3) {//编辑真正的员工，直接关闭
                    App.appViewModelInstance.getCreateFinish().setValue(true);
                    return;
                }
                if (!MMKVHelper.getBoolean(ConstantMMVK.IS_ENTRY_SIGN, false)) {
                    ToastUtil.showLong("入职信息将在审批通过后生效，请前往“待办”查看");
                    App.appViewModelInstance.getRefreshMember().setValue(true);
                    AppExtKt.finishActivity(AddProjectActivity.class);
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("uuid", "" + idCardMemberEntity.getUuid());
                ActivityForwardUtil.startActivity(SignHandActivity.class, bundle);
            }
        });

        mViewModel.getMembersDetailEntity().observe(this, new Observer<MembersDetailEntity>() {
            @Override
            public void onChanged(MembersDetailEntity membersDetailEntity) {
                uuid = membersDetailEntity.getUuid();
                fillData(membersDetailEntity.getHealthy_pic(), membersDetailEntity.getAvatar());
            }
        });

    }

    private void fillData(HealthyEntity healthyPic, String avatar) {
        if (!TextUtils.isEmpty(avatar)) {
            mPicAdapter.addItemData(avatar);
        }
        if (healthyPic != null) {
            for (int i = 0; i < healthyPic.getPic_list().size(); i++) {
                mUploadAdapter.addItemData(healthyPic.getPic_list().get(i).getSource_url());
            }
        }
    }


    private void requestCreate() {
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("op_type", "media");
        stringStringHashMap.put("uuid", uuid);
        if (mPicAdapter.getData().size() > 0) {
            stringStringHashMap.put("avatar", "" + mPicAdapter.getData().get(0));
        }
        if (mUploadAdapter.getData().size() > 0) {
            stringStringHashMap.put("healthy_pic", JSON.toJSONString(mUploadAdapter.getData()));
        }
        mViewModel.requestUpdateMembers(stringStringHashMap, AddProjectActivity.ID_PIC, type);
    }


}